package com.message.api.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.helper.StringUtils;
import com.message.api.base.dao.MsNoticeMapper;
import com.message.api.base.entity.MsNotice;
import com.message.api.base.entity.MsText;
import com.message.api.base.service.MsNoticeService;
import com.message.api.base.service.MsTextService;
import com.message.api.base.vo.MsNoticeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mzl
 * @since 2020-08-10
 */
@Service
public class MsNoticeServiceImpl extends ServiceImpl<MsNoticeMapper, MsNotice> implements MsNoticeService {

    @Autowired
    private MsTextService msTextService;

    @Override
    public List<MsNoticeVo> findByExample(MsNoticeVo example) {
        return this.baseMapper.findByExample(buildWrapper(example));
    }

    @Override
    public Page<MsNoticeVo> findByPage(MsNoticeVo example, Page page) {
        page.setOptimizeCountSql(false);
        return page.setRecords(this.baseMapper.findByExample(buildWrapper(example), page));
    }

    @Override
    public void saveNotice(MsNoticeVo notice) {
        MsText   msText   = msTextService.save(notice.getTextContent());
        MsNotice msNotice = notice;
        msNotice.setTextid(msText.getId());
        super.save(msNotice);
    }

    @Override
    public MsNotice setTop(Integer id, String top) {
        MsNotice msNotice = this.getById(id);
        if (null == msNotice || "0".equals(msNotice.getState())) {
            throw new RuntimeException("没有找到id对应对象");
        }
        if (top.equals(msNotice.getTop())) {
            throw new RuntimeException("该公告已经处于该状态");
        }
        msNotice.setTop(top);
        this.updateById(msNotice);
        return msNotice;
    }

    /**
     * 构建查询
     *
     * @param example
     * @return
     */
    private QueryWrapper<MsNoticeVo> buildWrapper(MsNoticeVo example) {
        QueryWrapper<MsNoticeVo> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(MsNotice::getState, "1")
                .orderByDesc(MsNotice::getTop)
                .orderByDesc(MsNotice::getId);

        //搜索公告标题或者公告内容
        wrapper.like(StringUtils.isNotEmpty(example.getTitle()), "title", example.getTitle())
                .or()
                .like(StringUtils.isNotEmpty(example.getTextContent()), "text_content", example.getTextContent());

        return wrapper;
    }

}
